$(function() {
    //获取用户信息
    getUserInfo()

    var layer = layui.layer

    $('#btnLogout').on('click', function() {
        layer.confirm('确定退出？', { icon: 3, title: '提示' },
            function(index) {
                //do something
                //1.清空本地存储中的 token
                localStorage.removeItem('token');
                //2.重新跳转到登录页面
                location.href = './login.html'
                    //关闭询问框
                layer.close(index);
            }
        );

    })
})

function getUserInfo() {
    $.ajax({
        method: 'GET',
        url: '/my/userinfo',
        //headers 请求头
        // headers: {
        //     Authorization: localStorage.getItem('token') || ''
        // },
        success: function(res) {
            if (res.status !== 0) {
                return layui.layer.msg('获取用户信息失败!')
            }
            renderAvatar(res.data)
        },
        //无论成功还是失败都会回调complete
        // complete: function(res) {
        //     if (res.responseJSON.status === 1 && res.responseJSON.message === '身份认证失败！') {
        //         //1.强制清空token
        //         localStorage.removeItem('token');
        //         location.href = '/login.html';
        //     }
        // }

    })
}
//渲染用户头像
function renderAvatar(user) {
    var name = user.nickname || user.username;
    $('.welcome').html('欢迎&nbsp;&nbsp;' + name)
    if (user.user_pic !== null) {
        $('.layui-nav-img').attr('src', user.user_pic).show();
        $('.text-avatar').hide();
    } else {
        $('.layui-nav-img').hide();
        var first = name[0].toUpperCase();
        $('.text-avatar').html(first);
    }
}